﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
//new
using System.Security.Cryptography;
using System.Net.NetworkInformation;
using System.Globalization;
using Microsoft.Win32;
using System.Configuration;
using System.Xml;

namespace MyRegester
{
    /// <summary>
    /// 注册码管理类
    /// </summary>
    public class RegMgr
    {
        private const string REGNODE = @"software\jari_its\";
        public static string m_LocalIP = "";
        public static string m_RegNode = "";
        public static string m_MachineCode="";
        public static string m_RegCode="";
        public RegMgr()
        {

        }

        /// <summary>
        /// 软件注册标记
        /// </summary>
        public static bool SoftRegstered
        {
            get
            {
                return Check();
            }
        }

        /// <summary>
        /// 检查软件是否注册
        /// </summary>
        /// <returns>返回True-注册  false-没有注册</returns>
        private static bool Check()
        {
            bool ans = false;
            try
            {
                string sn = ReadSN();
                if (m_LocalIP != "")
                {
                    string mac = GetMacAddress(m_LocalIP);
                    string oldmc = GetMachineCode(mac);
                    m_MachineCode = oldmc;
                    string md5in = GetNewMC(oldmc);
                    string md5out = getMd5Hash(md5in);
                    m_RegCode = md5out;
                    if (md5out == sn)
                    {
                        ans = true;
                    }
                }
            }
            catch { }
            return ans;
        }

        /// <summary>
        /// 生成新的机器码
        /// </summary>
        /// <param name="oldMC"></param>
        /// <returns></returns>
        public static string GetNewMC(string oldMC)
        {
            string newMC = "";
            for (int i = 0; i < oldMC.Length; i++)
            {
                newMC += Convert.ToChar(oldMC[i] * 2 + 3).ToString();
            }
            return newMC;
        }

        /// <summary>
        /// 根据Mac获取机器码
        /// </summary>
        /// <param name="Mac">Mac地址</param>
        /// <returns>机器码</returns>
        public static string GetMachineCode(string Mac)
        {
            string[] strings = Mac.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
            string newMac = "";
            for (int i = 0; i < strings.Length; i++)
            {
                int temp = int.Parse(strings[i], NumberStyles.HexNumber) * 3 + 3;
                newMac += temp.ToString();
            }
            return newMac;
        }

        /// <summary>
        /// 获取指定ip对应的mac地址
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static string GetMacAddress(string ip)
        {
            string Mac = "";
            bool found = false;
            try
            {
                NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
                if (nics != null || nics.Length > 0)
                {
                    foreach (NetworkInterface adapter in nics)
                    {
                        if (found)
                        {
                            break;
                        }
                        foreach (UnicastIPAddressInformation info in adapter.GetIPProperties().UnicastAddresses)
                        {
                            if (found)
                            {
                                break;
                            }
                            if (ip == info.Address.ToString())
                            {
                                found = true;
                                PhysicalAddress address = adapter.GetPhysicalAddress();
                                byte[] bytes = address.GetAddressBytes();
                                if ((bytes != null) && (bytes.Length == 6))
                                {
                                    string str = "";
                                    for (int i = 0; i < bytes.Length; i++)
                                    {
                                        str += bytes[i].ToString("X2");
                                        if (i != bytes.Length - 1)
                                        {
                                            str += "-";
                                        }
                                    }
                                    Mac = str;
                                }
                            }
                        }
                    }
                }
            }
            catch
            { }
            return Mac;
        }

        /// <summary>
        /// 获取本机所有的mac地址
        /// </summary>
        /// <returns></returns>
        private static List<string> GetMacAddress()
        {
            List<string> Mac = null;
            try
            {
                NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
                if (nics != null || nics.Length > 0)
                {
                    Mac = new List<string>(nics.Length);
                    foreach (NetworkInterface adapter in nics)
                    {
                        PhysicalAddress address = adapter.GetPhysicalAddress();
                        byte[] bytes = address.GetAddressBytes();
                        if ((bytes != null) && (bytes.Length == 6))
                        {
                            string str = "";
                            for (int i = 0; i < bytes.Length; i++)
                            {
                                str += bytes[i].ToString("X2");
                                if (i != bytes.Length - 1)
                                {
                                    str += "-";
                                }
                            }
                            Mac.Add(str);
                        }
                    }
                }
            }
            catch
            { }
            return Mac;
        }

        /// <summary>
        /// 读取注册码
        /// </summary>
        /// <returns></returns>
        private static string ReadSN()
        {
            string ans = "";
            try
            {
                RegistryKey reg = Registry.LocalMachine.OpenSubKey(REGNODE + m_RegNode, true);
                if (reg != null)
                {
                    ans = (string)reg.GetValue("SN", "");
                    reg.Close();
                }
            }
            catch
            { }
            return ans;
        }

        public static bool SetSN(string sn)
        {
            bool ans = false;
            try
            {
                Registry.LocalMachine.CreateSubKey(REGNODE + m_RegNode);
                RegistryKey reg = Registry.LocalMachine.OpenSubKey(REGNODE + m_RegNode, true);
                reg.SetValue("SN", sn);
                reg.Close();

                if (SoftRegstered)
                {
                    ans = true;
                }
            }
            catch
            { }
            return ans;
        }

        // Hash an input string and return the hash as
        // a 32 character hexadecimal string.
        public static string getMd5Hash(string input)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5 md5Hasher = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            string ans = sBuilder.ToString();
            ans = ans.Insert(24, "-");
            ans = ans.Insert(16, "-");
            ans = ans.Insert(8, "-");
            // Return the hexadecimal string.
            return ans;
        }

        // Verify a hash against a string.
        private static bool verifyMd5Hash(string input, string hash)
        {
            // Hash the input.
            string hashOfInput = getMd5Hash(input);

            // Create a StringComparer an comare the hashes.
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;

            if (0 == comparer.Compare(hashOfInput, hash))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}


